route.ts 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. import { NextRequest, NextResponse } from "next/server";
  2. import { auth } from "../../auth";
  3. import { getServerSideConfig } from "@/app/config/server";
  4. import { GEMINI_BASE_URL, Google } from "@/app/constant";
  5. async function handle(
  6. req: NextRequest,
  7. { params }: { params: { path: string[] } },
  8. ) {
  9. console.log("[Google Route] params ", params);
  10. if (req.method === "OPTIONS") {
  11. return NextResponse.json({ body: "OK" }, { status: 200 });
  12. }
  13. const controller = new AbortController();
  14. const serverConfig = getServerSideConfig();
  15. let baseUrl = serverConfig.googleUrl || GEMINI_BASE_URL;
  16. if (!baseUrl.startsWith("http")) {
  17. baseUrl = `https://${baseUrl}`;
  18. }
  19. if (baseUrl.endsWith("/")) {
  20. baseUrl = baseUrl.slice(0, -1);
  21. }
  22. let path = `${req.nextUrl.pathname}`.replaceAll("/api/google/", "");
  23. console.log("[Proxy] ", path);
  24. console.log("[Base Url]", baseUrl);
  25. // this fix [Org ID] undefined in server side if not using custom point
  26. if (serverConfig.openaiOrgId !== undefined) {
  27. console.log("[Org ID]", serverConfig.openaiOrgId);
  28. }
  29. const timeoutId = setTimeout(
  30. () => {
  31. controller.abort();
  32. },
  33. 10 * 60 * 1000,
  34. );
  35. const bearToken = req.headers.get("Authorization") ?? "";
  36. const token = bearToken.trim().replaceAll("Bearer ", "").trim();
  37. const key = token ? token : serverConfig.googleApiKey;
  38. if (!key) {
  39. return NextResponse.json(
  40. {
  41. error: true,
  42. message: `missing GOOGLE_API_KEY in server env vars`,
  43. },
  44. {
  45. status: 401,
  46. },
  47. );
  48. }
  49. const fetchUrl = `${baseUrl}/${path}?key=${key}`;
  50. const fetchOptions: RequestInit = {
  51. headers: {
  52. "Content-Type": "application/json",
  53. "Cache-Control": "no-store",
  54. },
  55. method: req.method,
  56. body: req.body,
  57. // to fix #2485: https://stackoverflow.com/questions/55920957/cloudflare-worker-typeerror-one-time-use-body
  58. redirect: "manual",
  59. // @ts-ignore
  60. duplex: "half",
  61. signal: controller.signal,
  62. };
  63. try {
  64. const res = await fetch(fetchUrl, fetchOptions);
  65. // to prevent browser prompt for credentials
  66. const newHeaders = new Headers(res.headers);
  67. newHeaders.delete("www-authenticate");
  68. // to disable nginx buffering
  69. newHeaders.set("X-Accel-Buffering", "no");
  70. return new Response(res.body, {
  71. status: res.status,
  72. statusText: res.statusText,
  73. headers: newHeaders,
  74. });
  75. } finally {
  76. clearTimeout(timeoutId);
  77. }
  78. }
  79. export const GET = handle;
  80. export const POST = handle;
  81. export const runtime = "edge";
  82. export const preferredRegion = [
  83. "arn1",
  84. "bom1",
  85. "cdg1",
  86. "cle1",
  87. "cpt1",
  88. "dub1",
  89. "fra1",
  90. "gru1",
  91. "hnd1",
  92. "iad1",
  93. "icn1",
  94. "kix1",
  95. "lhr1",
  96. "pdx1",
  97. "sfo1",
  98. "sin1",
  99. "syd1",
  100. ];